## File: cache-server.py
## Author: Dustin Dannenhauer
## Contact: dtdannen@indiana.edu
##
## This is a simple webserver that
## allows the user to query any database on the web
## by entering a SPARQL statement

# Web libraries
import web
from web import form

# rdf stuff
from rdflib import Graph
from SPARQLWrapper import SPARQLWrapper, JSON

# memoization
# from plone.memoize import forever

# timing
import time

urls = ('/', 'index')

app = web.application(urls, globals(), True)
render = web.template.render('templates/')

query_form = form.Form(
    form.Textbox('host'),
    form.Textarea('query',
                  web.form.notnull,
                  rows=15, cols=60,
                  description="QUERY ",))

class index:
    def GET(self):
        print "recieved a get request"
        my_form = query_form()
        return render.hello(my_form)

    def POST(self):
        print "recieved a post request"
        my_form = query_form() 
        if not my_form.validates(): 
            return render.hello(my_form)
        else:
        #    prefix_entry = my_form['prefix'].value
        #    select_entry = my_form['select'].value
        #    where_entry = my_form['where'].value
            host_entry = my_form['host'].value
            query_entry = my_form['query'].value
        # call code for actual querying
            # display results of query, amount of time, number results, etc...

            #qry_str = prefix_entry +  " SELECT " + select_entry + " WHERE { " + where_entry + " } "
        #print "=================== Host Is ==================="
        #print host_entry
        #print "=================== Host END ==================="        
        #print "=================== Query Is ==================="
        #print query_entry
        #print "=================== Query END ==================="        

        qtime = time.time() 
        qresult = rdfActions().query(host_entry,query_entry)
        qtime = time.time() - qtime

        # Send the following string back to the person who just hit me
        return "Query took " + str(qtime) + " amount of time..." 


#GLOBAL CACHE
cache = {}

# Non webserver stuff, only for rdf queries
class rdfActions:

    #@forever.memoize
    # For now I'm going to implement my own caching mechanizm
    def query(self,host,query_str):
        
        if (host + query_str) in cache:
            print "found query in cache, quick retrieval"
            return cache[(host+query_str)]
        else:
            print "query NOT found in cache, will query then add..."
            print "starting query"
            sparql = SPARQLWrapper(host)
            sparql.setQuery(query_str)
            sparql.setReturnFormat(JSON)
            print "about to query...may take a few seconds"
            results = sparql.query().convert()
            print "finished querying, saving into cache"
            cache[(host+query_str)] = str(results)
            return str(results)
        
if __name__ == "__main__":
    web.internalerror = web.debugerror
    app.run()


